package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.UserConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserFollowService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {


    private final ApUserFollowMapper apUserFollowMapper;

    private final CacheService cacheService;

    private final ApUserMapper apUserMapper;

    /**
     * 关注 或者 取消关注作者
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult followApUser(UserRelationDto dto) {
        // 1、判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2、检查参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 3、执行业务
        String key= BehaviorConstants.FOLLOW_AUTHOR+"_"+dto.getAuthorId();;
        ApUserFollow apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(user.getId());
        apUserFollow.setFollowId(dto.getAuthorId());
        if(dto.getOperation()==0){
            // 关注
            apUserFollow.setLevel(ApUserFollow.LevelEnum.NORMAL.getLevel());
            apUserFollow.setIsNotice(Boolean.FALSE);
            // 查出作者name
            ApUser author = new ApUser();
            author.setId(dto.getAuthorId());
            author=apUserMapper.selectUserById(author);
            apUserFollow.setFollowName(author.getName());
            apUserFollow.setCreatedTime(new Date());
            apUserFollowMapper.saveFollow(apUserFollow);
            cacheService.hPut(key,user.getId().toString(), "0");
        }else{
            // 取消关注
            apUserFollowMapper.deleteFollow(apUserFollow);
            cacheService.hDelete(key,String.valueOf(user.getId()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
